package cameragps;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.decor.Border;
import net.rim.device.api.ui.decor.BorderFactory;

import net.rim.blackberry.api.invoke.Invoke;
import net.rim.blackberry.api.invoke.MessageArguments;
import net.rim.blackberry.api.pdap.BlackBerryContactList;

import javax.microedition.pim.Contact;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;
import javax.microedition.pim.PIMItem;

/**
 * This screen contains list of photos snapped by user he can forward them to
 * particular contact as well delete it
 */
public class MyPhotosScreen extends MainScreen {

	boolean canForwarAll = false;
	
	VerticalFieldManager scrollFieldManager = new VerticalFieldManager(
			USE_ALL_WIDTH | VERTICAL_SCROLL);

	public MyPhotosScreen() {
		super(MainScreen.NO_VERTICAL_SCROLL | MainScreen.NO_VERTICAL_SCROLLBAR);
		HorizontalFieldManager header = new HorizontalFieldManager(
				USE_ALL_WIDTH) {
			protected void sublayout(int maxWidth, int maxHeight) {
				super.sublayout(maxWidth, maxHeight);

				Field f = getField(1);
				layoutChild(f, f.getPreferredWidth(), getHeight());
				setPositionChild(f, getWidth() - f.getWidth() - 20, 0);

			}
		};
		header.setBackground(BackgroundFactory.createLinearGradientBackground(
				0x00BCE2F5, 0x00BCE2F5, 0x00ffffff, 0x00ffffff));

		header.setPadding(10, 10, 10, 10);

		header.add(new LabelField("My Photos", Field.FIELD_VCENTER));

		HorizontalFieldManager keepRight = new HorizontalFieldManager(
				Field.FIELD_VCENTER | USE_ALL_WIDTH);

		ButtonField forwardAllButtonField;

		

		for (int i = 0; i < ImageUtils.dataVector.size(); i++) {
			ImageInformation current = (ImageInformation) ImageUtils.dataVector
					.elementAt(i);
			if (current.isSent()) {
				canForwarAll = true;
				break;
			}
		}

		if (ImageUtils.accountString == null
				|| ImageUtils.accountString.equalsIgnoreCase(""))
			canForwarAll = false;

		if (canForwarAll) {
			forwardAllButtonField = new ButtonField("Forward All",
					Field.FIELD_RIGHT | ButtonField.CONSUME_CLICK);
			forwardAllButtonField.setChangeListener(new ForwardListener());
		} else {
			forwardAllButtonField = new ButtonField("Forward All",
					Field.FIELD_RIGHT | ButtonField.NON_FOCUSABLE) {
				protected void paint(Graphics graphics) {
					graphics.setColor(Color.GRAY);
					super.paint(graphics);
				}
			};
		}
		keepRight.add(forwardAllButtonField);

		ButtonField backButtonField = new ButtonField("Back", Field.FIELD_RIGHT
				| ButtonField.CONSUME_CLICK | USE_ALL_WIDTH);

		backButtonField.setChangeListener(new FieldChangeListener() {

			public void fieldChanged(Field field, int context) {
				close();
			}
		});

		keepRight.add(backButtonField);

		header.add(keepRight);

		this.add(header);

		for (int i = 0; i < ImageUtils.dataVector.size(); i++) {
			addRow((ImageInformation) ImageUtils.dataVector.elementAt(i));
		}

		this.add(scrollFieldManager);

	}

	/**
	 * @param current
	 *            an ImageInformation which is to be added in the list
	 * @param position
	 *            position of the ImageInformation in dataVector
	 * @see ImageUtils#dataVector
	 */
	private void addRow(ImageInformation current) {
		final String imageName = current.getField(ImageInformation.IMAGENAME);
		String location = current.getField(ImageInformation.LOCATION);
		String description = current.getField(ImageInformation.USERTEXT);

		final HorizontalFieldManager rowFieldManager = new HorizontalFieldManager(
				USE_ALL_WIDTH) {
			protected void sublayout(int maxWidth, int maxHeight) {
				super.sublayout(maxWidth, maxHeight);

				Field aField = getField(2);
				layoutChild(aField, aField.getPreferredWidth(), getHeight());
				setPositionChild(aField, getWidth() - aField.getWidth() - 20, 0);

				Field field = getField(1);
				layoutChild(field, getWidth() - aField.getPreferredWidth()
						- getField(0).getPreferredWidth() - 20, getHeight());
				setExtent(getWidth(), getHeight());
			}
		};
		rowFieldManager.setPadding(10, 10, 0, 10);
		rowFieldManager.setBorder(BorderFactory.createRoundedBorder(
				new XYEdges(5, 0, 0, 0), 0x00BCE2F5, Border.STYLE_SOLID));

		BitmapField imageIcon = new BitmapField(
				Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS), FIELD_TOP);

		
		try {
			imageIcon.setBitmap(Bitmap.createBitmapFromBytes(
					ImageUtils.getBytesFromImage(imageName), 0, -1, 5));
		} catch (Exception e) {
			return;
		}
		rowFieldManager.add(imageIcon);

		LabelField locationLabelField = new LabelField(location,
				LabelField.ELLIPSIS);
		LabelField descLabelField = new LabelField(description,
				LabelField.ELLIPSIS);

		VerticalFieldManager infoFieldManager = new VerticalFieldManager(
				FIELD_TOP);
		infoFieldManager.setMargin(10, 5, 10, 10);

		infoFieldManager.add(locationLabelField);
		infoFieldManager.add(descLabelField);

		rowFieldManager.add(infoFieldManager);

		VerticalFieldManager operationsField = new VerticalFieldManager(
				FIELD_TOP);

		ButtonField forwardButtonField;

		// if the user has successfully uploaded the pic then and then only he
		// is allowed to forward the image
		if (current.isSent() && canForwarAll) {
			forwardButtonField = new ButtonField("Forward", Field.FIELD_RIGHT
					| ButtonField.CONSUME_CLICK);
			forwardButtonField.setChangeListener(new ForwardListener(imageName,
					current.getField(ImageInformation.USERTEXT)));

		} else {
			forwardButtonField = new ButtonField("Forward", Field.NON_FOCUSABLE) {
				protected void paint(Graphics graphics) {
					graphics.setColor(Color.GRAY);
					super.paint(graphics);
				}
			};

			forwardButtonField.setVisualState(VISUAL_STATE_DISABLED);
		}

		operationsField.add(forwardButtonField);

		ButtonField deleteButtonField = new ButtonField("Delete",
				Field.FIELD_RIGHT | ButtonField.CONSUME_CLICK);
		deleteButtonField.setMinimalWidth(forwardButtonField.getWidth());
		deleteButtonField.setChangeListener(new FieldChangeListener() {

			public void fieldChanged(Field field, int context) {
				int response = Dialog.ask(Dialog.D_DELETE);
				if (response == Dialog.DELETE) {
					ImageUtils.deleteImage(imageName, rowFieldManager.getIndex());
					scrollFieldManager.delete(rowFieldManager);
				}
			}
		});

		operationsField.add(deleteButtonField);

		rowFieldManager.add(operationsField);

		scrollFieldManager.add(rowFieldManager);
	}

	protected boolean onSave() {
		return true;
	}

	protected boolean onSavePrompt() {

		return true;
	}

	/**
	 * listener that allow to send Email to a Contact
	 * 
	 * @author Dhruv Mewada
	 * 
	 */
	class ForwardListener implements FieldChangeListener {

		boolean forwardAll;
		//http://devweb.wearepassionfruit.com/nallu/images/
		private static final String IMAGES_URL = "http://worldbank.thetigerparty.com/Default.aspx?photo=";
		private String imageName;
		private String description;

		public ForwardListener(String imageName, String description) {

			forwardAll = false;

			this.imageName = imageName;
			this.description = description;
		}

		public ForwardListener() {
			forwardAll = true;

		}

		public void fieldChanged(Field field, int context) {

			if (ImageUtils.dataVector.size() <= 0)
				return;

			BlackBerryContactList list;
			try {
				list = (BlackBerryContactList) PIM.getInstance().openPIMList(
						PIM.CONTACT_LIST, PIM.READ_ONLY);

				PIMItem contact = list.choose();
				if (contact != null) {
					int count = contact.countValues(Contact.EMAIL);
					String[] emailIds = new String[count];
					int chosen = 0;

					switch (count) {
					case 0:
						Dialog.inform("There is no Email Address specified for this contact.");
						return;
					case 1:
						emailIds[0] = contact.getString(Contact.EMAIL, 0);
						break;
					default:

						int[] values = new int[count];
						for (int i = 0; i < contact.countValues(Contact.EMAIL); i++) {
							emailIds[i] = contact.getString(Contact.EMAIL, i);
							values[i] = i;
						}
						Dialog d = new Dialog("Choose Email",
								(Object[]) emailIds, values, 0, null,
								Dialog.LIST);
						chosen = d.doModal();

						break;
					}
					if (forwardAll)
						sendMail(emailIds[chosen]);
					else
						sendMail(emailIds[chosen], description);

				}
			} catch (PIMException e) {
				helloBerry.errorDialog("Proble creating contact list!" + e.getClass() + ": "
						+ e.getMessage());
			}
		}

		private void sendMail(String emailId, String description) {
			Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES,
					new MessageArguments(MessageArguments.ARG_NEW, emailId,
							"A photo I've snapped", description + "\n"
									+ IMAGES_URL + imageName));
		}

		private void sendMail(String emailId) {

			String message = "";

			for (int i = 0; i < ImageUtils.dataVector.size(); i++) {
				ImageInformation current = (ImageInformation) ImageUtils.dataVector
						.elementAt(i);
				if (current.isSent()) {
					message = message.concat(current
							.getField(ImageInformation.USERTEXT)
							+ " "
							+ IMAGES_URL
							+ current.getField(ImageInformation.IMAGENAME)
							+ "\n");
				}
			}

			Invoke.invokeApplication(Invoke.APP_TYPE_MESSAGES,
					new MessageArguments(MessageArguments.ARG_NEW, emailId,
							"Photos I've snapped\n", message));
		}
	}

}
